package com.ptl.bp.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.ptl.bp.dto.ImportError;
import com.ptl.bp.dto.PortableBatteryImportDTO;
import com.ptl.bp.entity.PortableBatteryEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@EqualsAndHashCode(callSuper = true)
@Data
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // 每次获取都是新实例
public class PortableBatteryImportListener extends AnalysisEventListener<PortableBatteryImportDTO> {
    private static final int BATCH_SIZE = 100;
    private final List<PortableBatteryImportDTO> successList = new ArrayList<>();
    private final List<ImportError> errorList = new ArrayList<>();
    @Resource
    private Validator getValidator;
    @Lazy
    @Resource
    private PortableBatteryService portableBatteryService;

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context);
    }

    @Override
    public void invoke(PortableBatteryImportDTO data, AnalysisContext context) {
        // 执行校验
        BindingResult bindingResult = new BeanPropertyBindingResult(data, PortableBatteryImportDTO.class.getSimpleName());
        getValidator.validate(data, bindingResult);

        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                int rowNum = context.readRowHolder().getRowIndex() + 1;
                errorList.add(new ImportError(rowNum, error.getDefaultMessage()));
            });
        } else {
            successList.add(data);
            // 达到BATCH_SIZE了，需要存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (successList.size() >= BATCH_SIZE) {
                saveData();
            }

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行: {}", exception.getMessage());
        Integer rowIndex = 0;
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            log.error("第{}行，第{}列解析异常", rowIndex, columnIndex);
        } else if (context != null && context.readRowHolder() != null) {
            rowIndex = context.readRowHolder().getRowIndex();  // 获取当前行号（如果支持）
            log.error("第{}行解析异常（非数据转换错误）", rowIndex);
        }
        errorList.add(new ImportError(rowIndex, exception.getMessage()));
    }

    private void saveData() {
        if (successList.isEmpty()) {
            return;
        }

        log.info("{}条数据开始存储数据库！", successList.size());

        // 获取所有需要处理的数据
        List<PortableBatteryEntity> entities = getSuccessList().stream()
                .map(v -> {
                    PortableBatteryEntity entity = new PortableBatteryEntity();
                    BeanUtils.copyProperties(v, entity);
                    return entity;
                })
                .collect(Collectors.toList());

        // 批量保存或更新
        portableBatteryService.saveOrUpdateBatch(entities);

        successList.clear();
    }
}